/*
 * User: rant
 * Date: Aug 1, 2007
 *
 *
 */
package laMalinche.actObservable;

import laMalinche.rete.conditions.FieldCondition;
import laMalinche.rete.nodes.StopEvaluatingException;
import laMalinche.rete.rule.Condition;
import laMalinche.rete.rule.ConditionObservable;
import laMalinche.DevMode;

import java.util.*;

import org.jetbrains.annotations.NotNull;

/**
 *
 */
public class BasicActObservableCondition extends BasicActObservable implements ConditionObservable {

    private final Condition condition;

    public BasicActObservableCondition(final Condition condition) {
         DevMode.getInstance().getInjector().injectMembers(this);
        this.condition = condition;
    }

    public @NotNull
    Condition getCondition() {
        return condition;
    }

    public boolean isDisjunction() {
        return condition.isDisjunction();
    }

    public boolean isComplied() {
        // todo make it null
        adviseStarted();
        boolean executed = true;
        boolean complied = false;
        try {
            complied = getCondition().isComplied();
        } catch (StopEvaluatingException e) {
            executed = false;
        } catch (Exception e) {
            adviseFinished(false);
           throw new RuntimeException(e);
        }
        adviseFinished(executed);
        if (!executed) {
            throw new StopEvaluatingException();
        }
        return complied;
    }

    @Override
    protected Set<String> getExcludedFields() {
        final Condition condition1 = getCondition();
        final Set<String> excludedF = new HashSet<String>();
        if (condition1.getClass().equals(FieldCondition.class)) {
            final String ognl = ((FieldCondition) condition1).getOgnl();
            excludedF.add(ognl);
        }
        return excludedF;
    }

    @Override
    public boolean equals(Object conditionAdapter) {
        return conditionAdapter instanceof BasicActObservableCondition &&
                getCondition().equals(((BasicActObservableCondition) conditionAdapter).getCondition()) ||
                conditionAdapter instanceof Condition && getCondition().equals(conditionAdapter);
    }

    @Override
    public int hashCode() {
        return getCondition().hashCode();
    }
}